use tvk_base::math::glam::Mat4;
use tvk_base::types::{Color, dpi::PhysicalSize};
use wgpu::util::DeviceExt as _;

use crate::wgpu::GRADIENT_SHADER_DEF;
use crate::wgpu::bind_groups::{BackgroundBindGroup, CameraBindGroup};

/// 背景渲染器 - 负责简单的梯度背景渲染
#[derive(Debug)]
pub struct BackgroundRenderer {
    pub camera_bind_group: CameraBindGroup,
    pub background_bind_group: BackgroundBindGroup,
    pub gradient_pipeline: wgpu::RenderPipeline,
    pub quad_geometry: BackgroundGeometry,
}

/// 背景几何体数据
#[derive(Debug)]
pub struct BackgroundGeometry {
    pub vertex_buffer: wgpu::Buffer,
    pub index_buffer: wgpu::Buffer,
    pub index_count: u32,
}

impl BackgroundRenderer {
    /// 创建新的背景渲染器
    pub fn new(
        device: &wgpu::Device,
        background_color: Option<Color<f64>>,
        surface_format: wgpu::TextureFormat,
    ) -> Self {
        // 创建相机绑定组
        let camera_layout = CameraBindGroup::create_layout(device);
        let camera_bind_group = CameraBindGroup::new(device, camera_layout);

        // 创建背景绑定组
        let background_layout = BackgroundBindGroup::create_layout(device);
        let background_bind_group =
            BackgroundBindGroup::new(device, background_layout, background_color);

        // 创建简单的梯度背景管线
        let gradient_pipeline = Self::create_gradient_pipeline(
            device,
            surface_format,
            &[
                &camera_bind_group.bind_group_layout,
                &background_bind_group.bind_group_layout,
            ],
        );

        // 创建全屏四边形几何体
        let quad_geometry = Self::create_fullscreen_quad(device);

        Self {
            camera_bind_group,
            background_bind_group,
            gradient_pipeline,
            quad_geometry,
        }
    }

    /// 创建简单的梯度背景管线
    fn create_gradient_pipeline(
        device: &wgpu::Device,
        surface_format: wgpu::TextureFormat,
        bind_group_layouts: &[&wgpu::BindGroupLayout],
    ) -> wgpu::RenderPipeline {
        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("Gradient Background Shader"),
            source: wgpu::ShaderSource::Wgsl(GRADIENT_SHADER_DEF.into()),
        });

        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("Gradient Background Pipeline Layout"),
            bind_group_layouts,
            push_constant_ranges: &[],
        });

        device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("Gradient Background Pipeline"),
            layout: Some(&pipeline_layout),
            vertex: wgpu::VertexState {
                module: &shader,
                entry_point: Some("vs_main"),
                buffers: &[wgpu::VertexBufferLayout {
                    array_stride: std::mem::size_of::<[f32; 2]>() as wgpu::BufferAddress,
                    step_mode: wgpu::VertexStepMode::Vertex,
                    attributes: &[wgpu::VertexAttribute {
                        format: wgpu::VertexFormat::Float32x2,
                        offset: 0,
                        shader_location: 0,
                    }],
                }],
                compilation_options: Default::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: &shader,
                entry_point: Some("fs_main"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: surface_format,
                    blend: Some(wgpu::BlendState::REPLACE),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: Default::default(),
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                strip_index_format: None,
                front_face: wgpu::FrontFace::Ccw,
                cull_mode: None, // 禁用剔除，确保四边形始终可见
                polygon_mode: wgpu::PolygonMode::Fill,
                unclipped_depth: false,
                conservative: false,
            },
            depth_stencil: Some(wgpu::DepthStencilState {
                format: wgpu::TextureFormat::Depth32Float,
                depth_write_enabled: false, // 背景不写入深度
                depth_compare: wgpu::CompareFunction::LessEqual, // 总是通过深度测试
                stencil: wgpu::StencilState::default(),
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: wgpu::MultisampleState {
                count: 1,
                mask: !0,
                alpha_to_coverage_enabled: false,
            },
            multiview: None,
            cache: None,
        })
    }

    /// 创建全屏四边形几何体
    fn create_fullscreen_quad(device: &wgpu::Device) -> BackgroundGeometry {
        // 全屏四边形的4个顶点（NDC坐标：[-1,1]范围）
        let vertices: [[f32; 2]; 4] = [
            [-1.0, -1.0], // 左下
            [1.0, -1.0],  // 右下
            [1.0, 1.0],   // 右上
            [-1.0, 1.0],  // 左上
        ];

        // 两个三角形组成四边形
        let indices: [u32; 6] = [0, 1, 2, 2, 3, 0];

        let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("Fullscreen Quad Vertex Buffer"),
            contents: bytemuck::cast_slice(&vertices),
            usage: wgpu::BufferUsages::VERTEX,
        });

        let index_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("Fullscreen Quad Index Buffer"),
            contents: bytemuck::cast_slice(&indices),
            usage: wgpu::BufferUsages::INDEX,
        });

        BackgroundGeometry {
            vertex_buffer,
            index_buffer,
            index_count: indices.len() as u32,
        }
    }

    /// 设置新的尺寸（对于简单梯度背景，不需要特殊处理）
    pub fn set_size(&mut self, _device: &wgpu::Device, _size: PhysicalSize<u32>) {
        // 简单梯度背景不需要根据尺寸调整几何体
        // 全屏四边形始终覆盖整个视口
    }

    /// 更新背景颜色
    pub fn update_background_color(&self, queue: &wgpu::Queue, background_color: Color<f64>) {
        self.background_bind_group
            .update_background_color(queue, background_color);
    }

    /// 更新相机矩阵
    pub fn update_camera_matrices(
        &self,
        queue: &wgpu::Queue,
        view_matrix: Mat4,
        proj_matrix: Mat4,
    ) {
        self.camera_bind_group.update_view(queue, view_matrix);
        self.camera_bind_group.update_proj(queue, proj_matrix);

        // 对于全屏四边形，模型矩阵始终为单位矩阵
        self.camera_bind_group.update_model(queue, Mat4::IDENTITY);
    }

    /// 绘制背景
    pub fn draw(&self, render_pass: &mut wgpu::RenderPass) {
        render_pass.set_pipeline(&self.gradient_pipeline);
        render_pass.set_bind_group(0, &self.camera_bind_group.bind_group, &[]);
        render_pass.set_bind_group(1, &self.background_bind_group.bind_group, &[]);
        render_pass.set_vertex_buffer(0, self.quad_geometry.vertex_buffer.slice(..));
        render_pass
            .set_index_buffer(self.quad_geometry.index_buffer.slice(..), wgpu::IndexFormat::Uint32);

        // 修正绘制范围：使用正确的索引范围
        render_pass.draw_indexed(0..self.quad_geometry.index_count, 0, 0..1);

        // println!("绘制梯度背景 - 索引数量: {}", self.quad_geometry.index_count);
    }
}
